package com.it.sun.esaychat.file.service;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.it.sun.esaychat.file.config.FastDfsProperties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author sunmannian
 * @ClassName com.it.sun.easychat.common.fastdfs.FastDfsClient
 * @Date 2020/5/28 14:53
 * @Version V1.0
 * Description  <请输入一句话描述该类功能>
 * Copyright (C) 北京中电兴发科技有限公司  since 2020/5/28
 */
@Service
public class FastDfsServices {

    @Autowired
    private FastDfsProperties properties;

    @Autowired
    private FastFileStorageClient storageClient;


    public String uploadFile(File file) throws IOException {
        StorePath storePath = storageClient.uploadFile(FileUtils.openInputStream(file),
                file.length(),
                FilenameUtils.getExtension(file.getName()),
                null);
        return getRealPath(storePath);
    }

    /**
     * <描述方法功能>
     * <上传文件>
     *
     * @param file
     * @return java.lang.String
     * @Author sunmannian
     * @Description
     * @Date 2020/5/28 15:16
     **/
    public StorePath uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(),
                file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()),
                null);
        return storePath;
    }

    public String getRealPath(StorePath storePath) {
        return properties.getHost() + storePath.getFullPath();
    }
}
